import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:photo_pipeline/photo_pipeline.dart';
import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import '../constants/colors.dart';
import '../constants/text_styles.dart';
import '../providers/pipeline_providers.dart';

/// 照片查看器页面
class PhotoViewerScreen extends ConsumerStatefulWidget {
  final List<String> photos;
  final int initialIndex;
  final List<String>? titles;
  final List<int>? fileIds; // 文件 ID 列表，用于订阅下载进度和数据库变化

  const PhotoViewerScreen({
    super.key,
    required this.photos,
    this.initialIndex = 0,
    this.titles,
    this.fileIds,
  });

  @override
  ConsumerState<PhotoViewerScreen> createState() => _PhotoViewerScreenState();
}

class _PhotoViewerScreenState extends ConsumerState<PhotoViewerScreen>
    with SingleTickerProviderStateMixin {
  late PageController _pageController;
  late int _currentIndex;
  final TransformationController _transformationController =
      TransformationController();
  late AnimationController _animationController;
  Animation<Matrix4>? _animation;

  // 下拉关闭相关
  double _dragOffset = 0.0;
  double _dragOpacity = 1.0;
  bool _isDragging = false;

  // 缓存完成提示相关（用于当前索引的完成提示）
  bool _showCacheComplete = false;
  Timer? _cacheCompleteTimer;
  int? _lastCompleteFileId; // 记录最后显示完成提示的文件 ID
  // 简单的缩略图内存缓存，避免每次重建都重新 base64 解码导致闪烁
  final Map<int, Uint8List> _thumbnailBytesCache = <int, Uint8List>{};

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex;
    _pageController = PageController(initialPage: widget.initialIndex);
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 250),
    )..addListener(() {
        if (_animation != null) {
          _transformationController.value = _animation!.value;
        }
      });

    // 初始化时触发初始页面的原图下载
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _triggerDownloadForIndex(widget.initialIndex);
    });
  }

  /// 触发指定索引的原图下载
  void _triggerDownloadForIndex(int index) {
    if (widget.fileIds == null || index >= widget.fileIds!.length) {
      return;
    }

    final fileId = widget.fileIds![index];
    if (fileId == null) return;

    // 异步获取 FileInfo 并触发下载
    // 使用 fileInfoProvider 获取文件信息
    ref.read(fileInfoProvider(fileId).future).then((fileInfo) {
      if (fileInfo != null) {
        // 检查原图是否已存在
        final imagePath = fileInfo.path;
        final hasOriginalImage =
            imagePath != null && File(imagePath).existsSync();

        // 如果原图不存在，触发下载
        if (!hasOriginalImage) {
          final controller = ref.read(pipelineControllerProvider);
          controller.camera.downloadEmergency(fileInfo).catchError((e) {
            debugPrint('[PhotoViewerScreen] 下载原图失败: $e');
          });
        }
      }
    }).catchError((e) {
      debugPrint('[PhotoViewerScreen] 获取文件信息失败: $e');
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    _transformationController.dispose();
    _animationController.dispose();
    _cacheCompleteTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 获取当前索引的文件 ID（用于缓存完成提示的逻辑判断）
    final currentFileId =
        widget.fileIds != null && _currentIndex < widget.fileIds!.length
            ? widget.fileIds![_currentIndex]
            : null;

    // 订阅当前文件的下载进度（仅用于缓存完成提示逻辑，不影响图片重建）
    final progressAsync = currentFileId != null
        ? ref.watch(fileCacheProgressProvider(currentFileId))
        : const AsyncValue<FileCacheProgress?>.data(null);

    final fileInfoAsync = currentFileId != null
        ? ref.watch(fileInfoProvider(currentFileId))
        : const AsyncValue<FileInfo?>.data(null);

    final currentProgress = progressAsync.valueOrNull;
    final currentFileInfo = fileInfoAsync.valueOrNull;

    // 检测缓存是否完成（原图已存在）
    final isCacheComplete = currentFileInfo != null &&
        currentFileInfo.path != null &&
        File(currentFileInfo.path!).existsSync();
    // 检测是否正在下载（有进度且进度小于100%）
    final isDownloading =
        currentProgress != null && currentProgress.progressPercent < 100;

    // 缓存完成提示的逻辑：如果缓存完成且之前正在下载（现在不下载了），显示完成提示
    if (isCacheComplete &&
        !isDownloading &&
        currentProgress != null &&
        currentFileId != null) {
      if (currentFileId != _lastCompleteFileId) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted &&
              !_showCacheComplete &&
              currentFileId == widget.fileIds?[_currentIndex]) {
            setState(() {
              _showCacheComplete = true;
              _lastCompleteFileId = currentFileId;
            });
            _cacheCompleteTimer?.cancel();
            _cacheCompleteTimer = Timer(const Duration(seconds: 2), () {
              if (mounted) {
                setState(() {
                  _showCacheComplete = false;
                });
              }
            });
          }
        });
      }
    }

    // 如果开始新的下载，隐藏完成提示
    if (isDownloading &&
        _showCacheComplete &&
        currentFileId == _lastCompleteFileId) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          setState(() {
            _showCacheComplete = false;
            _lastCompleteFileId = null;
          });
          _cacheCompleteTimer?.cancel();
        }
      });
    }

    // 如果缓存完成且没有进度记录（一开始就有缓存），不显示完成提示
    if (isCacheComplete &&
        currentProgress == null &&
        _showCacheComplete &&
        currentFileId == _lastCompleteFileId) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          setState(() {
            _showCacheComplete = false;
            _lastCompleteFileId = null;
          });
          _cacheCompleteTimer?.cancel();
        }
      });
    }

    // 如果切换到了不同的文件，确保不显示前一个文件的完成提示
    if (currentFileId != null &&
        currentFileId != _lastCompleteFileId &&
        _showCacheComplete) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          setState(() {
            _showCacheComplete = false;
            _lastCompleteFileId = null;
          });
          _cacheCompleteTimer?.cancel();
        }
      });
    }

    return Scaffold(
      backgroundColor: Colors.black.withOpacity(_dragOpacity),
      body: GestureDetector(
        onVerticalDragStart: (details) {
          // 只有在1倍缩放时才允许下拉关闭
          final currentScale =
              _transformationController.value.getMaxScaleOnAxis();
          if (currentScale <= 1.01) {
            setState(() {
              _isDragging = true;
            });
          }
        },
        onVerticalDragUpdate: (details) {
          if (!_isDragging) return;

          setState(() {
            _dragOffset += details.delta.dy;
            // 限制只能向下拖
            if (_dragOffset < 0) _dragOffset = 0;

            // 根据拖动距离计算透明度
            final progress = (_dragOffset / 300).clamp(0.0, 1.0);
            _dragOpacity = 1.0 - (progress * 0.5);
          });
        },
        onVerticalDragEnd: (details) {
          if (!_isDragging) return;

          setState(() {
            _isDragging = false;
          });

          // 如果拖动超过150或速度足够快，则关闭
          if (_dragOffset > 150 || details.velocity.pixelsPerSecond.dy > 500) {
            Navigator.pop(context);
          } else {
            // 否则回弹
            setState(() {
              _dragOffset = 0.0;
              _dragOpacity = 1.0;
            });
          }
        },
        child: Transform.translate(
          offset: Offset(0, _dragOffset),
          child: Stack(
            children: [
              // 图片查看器
              PageView.builder(
                controller: _pageController,
                itemCount: widget.photos.length,
                physics:
                    _isDragging ? const NeverScrollableScrollPhysics() : null,
                onPageChanged: (index) {
                  setState(() {
                    _currentIndex = index;
                    _transformationController.value = Matrix4.identity();
                  });

                  // 切换文件时重置缓存完成提示状态
                  if (_showCacheComplete) {
                    _cacheCompleteTimer?.cancel();
                    _showCacheComplete = false;
                    _lastCompleteFileId = null;
                  }

                  // 滑动切换时触发原图下载
                  _triggerDownloadForIndex(index);
                },
                itemBuilder: (context, index) {
                  final fileId =
                      widget.fileIds != null && index < widget.fileIds!.length
                          ? widget.fileIds![index]
                          : null;
                  // 为每个索引订阅对应的文件信息，而不是只使用当前索引的文件信息
                  return _buildPhotoViewerItem(index, fileId);
                },
              ),

              // 顶部标题栏
              SafeArea(
                child: Container(
                  height: 56,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.black.withOpacity(0.6),
                        Colors.transparent,
                      ],
                    ),
                  ),
                  child: Row(
                    children: [
                      // 返回按钮
                      IconButton(
                        icon: const Icon(
                          Icons.arrow_back,
                          color: Colors.white,
                        ),
                        onPressed: () => Navigator.pop(context),
                      ),

                      // 标题
                      Expanded(
                        child: Text(
                          _getTitle(_currentIndex),
                          style: AppTextStyles.heading3.copyWith(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),

                      // 占位，保持标题居中
                      const SizedBox(width: 48),
                    ],
                  ),
                ),
              ),

              // 底部指示器（圆形进度条覆盖在图片上方，不需要调整位置）
              if (widget.photos.length > 1)
                Positioned(
                  left: 0,
                  right: 0,
                  bottom: _showCacheComplete ? 100 : 40, // 如果有完成提示，指示器位置更高
                  child: Center(
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 6,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.6),
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Text(
                        '${_currentIndex + 1} / ${widget.photos.length}',
                        style: AppTextStyles.body2.copyWith(
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ),

              // 缓存完成提示（完成后显示2秒，然后自动消失）
              if (_showCacheComplete && isCacheComplete)
                Positioned(
                  left: 0,
                  right: 0,
                  bottom: 40,
                  child: SafeArea(
                    child: Center(
                      child: AnimatedOpacity(
                        opacity: _showCacheComplete ? 1.0 : 0.0,
                        duration: const Duration(milliseconds: 300),
                        child: Container(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 20, vertical: 12),
                          decoration: BoxDecoration(
                            color: Colors.green.withOpacity(0.9),
                            borderRadius: BorderRadius.circular(20),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              const Icon(
                                Icons.check_circle,
                                color: Colors.white,
                                size: 20,
                              ),
                              const SizedBox(width: 8),
                              Text(
                                '缓存完成',
                                style: AppTextStyles.body2.copyWith(
                                  color: Colors.white,
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建每个索引的图片查看器项（为每个索引订阅对应的文件信息和下载进度）
  Widget _buildPhotoViewerItem(int index, int? fileId) {
    if (fileId == null) {
      return _buildPhotoViewer(index, null, null, null);
    }

    // 外层仅订阅文件信息，避免进度变化引起图片重建
    return Consumer(
      builder: (context, ref, _) {
        final fileInfoAsync = ref.watch(fileInfoProvider(fileId));
        final fileInfo = fileInfoAsync.valueOrNull;

        // 进度覆盖使用单独的 Consumer，避免影响图片部分
        return Stack(
          children: [
            _buildPhotoViewer(index, fileId, fileInfo, null),
            Consumer(
              builder: (context, ref2, __) {
                final progressAsync =
                    ref2.watch(fileCacheProgressProvider(fileId));
                final progress = progressAsync.valueOrNull;
                if (progress == null || progress.progressPercent >= 100) {
                  return const SizedBox.shrink();
                }
                final isCurrentIndex = index == _currentIndex;
                return Positioned.fill(
                  child: IgnorePointer(
                    ignoring: true,
                    child: Center(
                      child: _buildProgressOverlay(progress, isCurrentIndex),
                    ),
                  ),
                );
              },
            ),
          ],
        );
      },
    );
  }

  Widget _buildPhotoViewer(
      int index, int? fileId, FileInfo? fileInfo, FileCacheProgress? progress) {
    // 如果是当前索引，使用 TransformationController（支持缩放）
    final isCurrentIndex = index == _currentIndex;
    final transformationController =
        isCurrentIndex ? _transformationController : TransformationController();

    if (fileId != null && fileInfo != null) {
      final imagePath = fileInfo.path;
      final thumbnailPath = fileInfo.thumbnailPath;

      // 检查文件是否已下载完成（path 存在且文件存在）
      final hasOriginalImage =
          imagePath != null && File(imagePath).existsSync();

      // 检查是否有下载进度且未完成
      // 注意：如果 path 已经更新，说明下载已完成，即使进度记录还在也忽略
      final hasProgress = hasOriginalImage
          ? false
          : (progress != null &&
              progress.progressPercent >= 0 &&
              progress.progressPercent < 100);

      // 调试输出：检查进度信息
      if (progress != null) {
        debugPrint(
            '[PhotoViewerScreen] item $index: progress=${progress.progressPercent}%, hasProgress=$hasProgress, isCurrentIndex=$isCurrentIndex');
      }

      return SizedBox.expand(
        child: GestureDetector(
          onDoubleTap: isCurrentIndex ? _handleDoubleTap : null,
          child: InteractiveViewer(
            transformationController: transformationController,
            minScale: isCurrentIndex ? 1.0 : 1.0,
            maxScale: isCurrentIndex ? 3.0 : 1.0,
            boundaryMargin: const EdgeInsets.all(0),
            panEnabled: isCurrentIndex,
            scaleEnabled: isCurrentIndex,
            child: Container(
              width: double.infinity,
              height: double.infinity,
              color: Colors.black,
              child: AnimatedSwitcher(
                duration: const Duration(milliseconds: 200),
                switchInCurve: Curves.easeOut,
                switchOutCurve: Curves.easeIn,
                child: hasOriginalImage
                    ? Image.file(
                        File(imagePath),
                        key: ValueKey('original_$fileId'),
                        fit: BoxFit.contain,
                        width: double.infinity,
                        height: double.infinity,
                        gaplessPlayback: true,
                        errorBuilder: (context, error, stackTrace) {
                          return _buildThumbnailOrPlaceholder(
                              thumbnailPath, fileId);
                        },
                      )
                    : _buildThumbnailOrPlaceholder(thumbnailPath, fileId),
              ),
            ),
          ),
        ),
      );
    }

    // 默认显示占位图
    return SizedBox.expand(
      child: GestureDetector(
        onDoubleTap: isCurrentIndex ? _handleDoubleTap : null,
        child: InteractiveViewer(
          transformationController: transformationController,
          minScale: isCurrentIndex ? 1.0 : 1.0, // 非当前索引限制缩放
          maxScale: isCurrentIndex ? 3.0 : 1.0, // 非当前索引禁止缩放
          boundaryMargin: const EdgeInsets.all(0),
          panEnabled: isCurrentIndex, // 只有当前索引才能平移
          scaleEnabled: isCurrentIndex, // 只有当前索引才能缩放
          child: Container(
            width: double.infinity,
            height: double.infinity,
            color: Colors.black,
            child: _buildPhotoPlaceholder(),
          ),
        ),
      ),
    );
  }

  /// 构建缩略图或占位符（优先显示缩略图）
  Widget _buildThumbnailOrPlaceholder(String? thumbnailPath, int? fileId) {
    if (thumbnailPath == null || thumbnailPath.isEmpty) {
      return _buildPhotoPlaceholder();
    }

    try {
      if (fileId != null && _thumbnailBytesCache.containsKey(fileId)) {
        return Image.memory(
          _thumbnailBytesCache[fileId]!,
          key: ValueKey('thumbnail_$fileId'),
          fit: BoxFit.contain,
          width: double.infinity,
          height: double.infinity,
          gaplessPlayback: true,
          errorBuilder: (context, error, stackTrace) {
            return _buildPhotoPlaceholder();
          },
        );
      }

      final data = thumbnailPath.contains(',')
          ? thumbnailPath.split(',').last
          : thumbnailPath;
      final thumbnailBytes = base64Decode(data);
      if (fileId != null) {
        _thumbnailBytesCache[fileId] = thumbnailBytes;
      }

      return Image.memory(
        thumbnailBytes,
        key: ValueKey('thumbnail_$fileId'),
        fit: BoxFit.contain,
        width: double.infinity,
        height: double.infinity,
        gaplessPlayback: true,
        errorBuilder: (context, error, stackTrace) {
          return _buildPhotoPlaceholder();
        },
      );
    } catch (e) {
      // base64 解码失败，显示占位符
      return _buildPhotoPlaceholder();
    }
  }

  String _formatBytes(int bytes) {
    if (bytes < 1024) return '$bytes B';
    if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    }
    return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
  }

  /// 处理双击缩放
  void _handleDoubleTap() {
    // 获取当前缩放值
    final Matrix4 currentMatrix = _transformationController.value;
    final double currentScale = currentMatrix.getMaxScaleOnAxis();

    // 判断当前缩放级别，在1倍和2倍之间切换
    final double targetScale = currentScale > 1.5 ? 1.0 : 2.0;

    // 创建新的变换矩阵
    Matrix4 targetMatrix;
    if (targetScale == 2.0) {
      // 放大到2倍，居中显示
      // 获取屏幕尺寸
      final Size screenSize = MediaQuery.of(context).size;

      // 计算居中所需的偏移量
      // 当放大2倍时，图片尺寸变为2倍，需要将图片中心移到屏幕中心
      // 偏移量 = (屏幕尺寸 - 图片尺寸 * 缩放) / 2
      // 简化为：偏移量 = 屏幕尺寸 * (1 - 缩放) / 2
      final double translateX = screenSize.width * (1 - targetScale) / 2;
      final double translateY = screenSize.height * (1 - targetScale) / 2;

      targetMatrix = Matrix4.identity()
        ..translate(translateX, translateY)
        ..scale(targetScale);
    } else {
      // 缩回1倍
      targetMatrix = Matrix4.identity();
    }

    // 创建补间动画
    _animation = Matrix4Tween(
      begin: currentMatrix,
      end: targetMatrix,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));

    // 重置并启动动画
    _animationController.reset();
    _animationController.forward();
  }

  /// 构建照片占位图（暂时用灰色方块代替）
  Widget _buildPhotoPlaceholder() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: const BoxDecoration(
        color: Colors.black,
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.image,
              size: 80,
              color: Colors.grey[600],
            ),
            const SizedBox(height: 16),
            Text(
              _getTitle(_currentIndex),
              style: AppTextStyles.body1.copyWith(
                color: Colors.grey[500],
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _getTitle(int index) {
    if (widget.titles != null && index < widget.titles!.length) {
      return widget.titles![index];
    }
    return 'FUJIfil...${index + 1}.JPG';
  }

  Widget _buildProgressOverlay(
      FileCacheProgress progress, bool isCurrentIndex) {
    return Container(
      width: isCurrentIndex ? 100 : 80,
      height: isCurrentIndex ? 100 : 80,
      decoration: BoxDecoration(
        color: Colors.black.withOpacity(0.7),
        shape: BoxShape.circle,
      ),
      child: Stack(
        children: [
          Center(
            child: SizedBox(
              width: isCurrentIndex ? 80 : 60,
              height: isCurrentIndex ? 80 : 60,
              child: CircularProgressIndicator(
                value: progress.progressPercent / 100.0,
                backgroundColor: Colors.grey[700],
                valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
                strokeWidth: isCurrentIndex ? 5 : 4,
              ),
            ),
          ),
          Center(
            child: isCurrentIndex
                ? Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        '${progress.progressPercent}%',
                        style: AppTextStyles.body2.copyWith(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        '${_formatBytes(progress.cachedBytes)} / ${_formatBytes(progress.totalBytes)}',
                        style: AppTextStyles.body2.copyWith(
                          color: Colors.white70,
                          fontSize: 10,
                        ),
                      ),
                    ],
                  )
                : Text(
                    '${progress.progressPercent}%',
                    style: AppTextStyles.body2.copyWith(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
          ),
        ],
      ),
    );
  }
}
